package com.yunfei.api.upload;

import com.yunfei.api.smrz.bo.AppFileBo;
import com.yunfei.api.upload.contants.UploadContants;
import com.yunfei.api.upload.param.ListUploadParam;
import com.yunfei.api.upload.param.UploadParam;
import com.yunfei.bo.crmAcceDtl.CrmAcceDtlBo;
import com.yunfei.bo.result.ResultModel;
import com.yunfei.enums.ResultStatus;
import com.yunfei.mapper.aiiidb.CrmAcceDtlMapper;
import com.yunfei.mapper.aiiidb.HeGeTouZiZheRenZhengMapper;
import com.yunfei.mapper.aiiidb.ShiMingRenZhengUploadMapper;
import com.yunfei.mapper.crm.TblobtSorageMapper;
import com.yunfei.utils.DateUtil;
import com.yunfei.utils.contants.ApplicationConstant;
import com.yunfei.utils.string.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("ALL")
@Controller
@Api(value = "实名认证文件上传",tags = "实名认证文件上传(理财师发起)")
public class ShiMingRenZhengUploadImageApiController {
    @Autowired
    private Environment env;
    @Autowired
    private TblobtSorageMapper tblobtSorageMapper;
    @Autowired
    private ShiMingRenZhengUploadMapper shiMingRenZhengUploadMapper;
    @Autowired
    private CrmAcceDtlMapper crmAcceDtlMapper;
    @Autowired
    private HeGeTouZiZheRenZhengMapper heGeTouZiZheRenZhengMapper;
    /**
    * @Description: 通用图片上传，附件上传接口
    * @Param: uploadType 图片上传类型：
    * @Param: lStorageid 附件ID
    * @Param: pReasonInfo2 实名认证接口返回的pReasonInfo2
     * PROD -产品
     * NEWS -资讯
     * SHOP -商城
     * VIDEO -视频
     * PRODANSW -产品回复
     * CLUB -秀实俱乐部
     * CRM --CRM附件
    * @return: void
    * @Author: zhengyunfei
    * @Date: 2019/1/25
    * @time:10:32
    */
    @RequestMapping(value = "/api/upload",method = RequestMethod.POST)
    @Transactional
    @ResponseBody
    @ApiOperation(value = "单文件上传",notes = "单文件上传",position = 1,response = Object.class)
    public ResultModel saveCardPic(HttpServletRequest request, HttpServletResponse response, UploadParam uploadParam){
         String uploadType=uploadParam.getUploadType();
         if(StringUtil.isNullOrEmpty(uploadType)){
             uploadType= UploadContants.UPLOAD_TYPE_CRM;
         }
         int index=uploadParam.getFileCount();
         String pReasonInfo2=uploadParam.getpReasonInfo2();
         String cCustNo=uploadParam.getcCustNo();
        ResultModel resultModel=new ResultModel();
        response.setHeader("Access-Control-Allow-Origin", "*");
        String uploadPath = env.getProperty(ApplicationConstant.FILE_IMAGE_PATH);
        String imageDomain = env.getProperty(ApplicationConstant.IMAGE_SERVER_DOMAIN) + "files/";
        String lStorageid=tblobtSorageMapper.getTblobStorageSeq()+"";
        List<AppFileBo> appFileList=new ArrayList<>();
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            // 获得第1张图片（根据前台的name名称得到上传的文件）
            MultipartFile imgFile1 = multipartHttpServletRequest.getFile("file");
                if (!imgFile1.isEmpty()) {
                    //获取前端传来的文件名
                    String fileName = imgFile1.getOriginalFilename();
                    // 设置存放图片文件的路径
                    String today= DateUtil.getToDay();
                    try {
                        AppFileBo appFileBo=new AppFileBo();
                        appFileBo.setlStorageid(lStorageid);
                        appFileBo.setUserId(cCustNo);
                        String fileExt = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length());
                        appFileBo.setcFilename(fileName);//文件名
                        appFileBo.setcFileSize(imgFile1.getSize()+"");//文件大小
                        String prex=lStorageid.substring(0,lStorageid.length()-1);
                        String filePath=uploadPath+uploadType+"/"+today+"/Tblobstorage/"+prex+"/"+appFileBo.getlStorageid()+"."+fileExt;
                        appFileBo.setcFilepath(filePath);
                        try {
                            //利用文件流保存文件
                            File saveFile= new File(filePath);
                            File parentFile=saveFile.getParentFile();
                            if(!parentFile.exists()&&!parentFile.isDirectory()){
                                parentFile.mkdirs();
                            }
                            if(!saveFile.exists())
                            {
                                try {
                                    saveFile.createNewFile();
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                            imgFile1.transferTo(saveFile);
                            System.out.println("文件上传路径："+filePath);
                            String appFileName=appFileBo.getlStorageid()+"."+fileExt;
                            String fileUrl = imageDomain  + "/" +today+"/Tblobstorage/"+prex+"/"+appFileName;
                            appFileBo.setFileUrl(fileUrl);
                            appFileBo.setAppFileName(appFileName);
                            System.out.println("文件访问地址=========="+fileUrl);
                            //保存文件到crm数据库
                            if(!StringUtil.isNullOrEmpty(pReasonInfo2)){
                                appFileBo.setcSubkeyId(pReasonInfo2);
                            }else{
                                Map<String,Object> subKeyIdMap=new HashMap<>();
                                subKeyIdMap.put("cCustNo",cCustNo);
                                String cSubKeyId=crmAcceDtlMapper.getCSubKeyId(subKeyIdMap);
                                if(StringUtil.isNullOrEmpty(cSubKeyId)){
                                    cSubKeyId="";
                                }
                                appFileBo.setcSubkeyId(cSubKeyId);
                            }

                            Map<String,Object> queryMap=new HashMap<>();
                            queryMap.put("userId",appFileBo.getUserId());
                            String deptNodeCode=shiMingRenZhengUploadMapper.getDeptNodeCode(queryMap);
                            if(StringUtil.isNullOrEmpty(deptNodeCode)){
                                deptNodeCode="";
                            }
                            appFileBo.setDeptNodeCode(deptNodeCode);
                            //实名认证文件处理
                            if(index==0){
                                appFileBo.setcCataLog("TCUSTREGISTERREQ_MAIN");
                                String lStrorageId=shiMingRenZhengUploadMapper.getLstrorageId(appFileBo);
                                appFileBo.setlStorageid(lStrorageId);
                                shiMingRenZhengUploadMapper.insertFirst(appFileBo);
                            }else{
                                appFileBo.setcCataLog("TCUSTREGISTERREQ");
                                shiMingRenZhengUploadMapper.insertSecond(appFileBo);
                            }
                            //保存文件附件到app数据库
                            CrmAcceDtlBo crmAcceDtlBo=new CrmAcceDtlBo();
                            crmAcceDtlBo.setLStorageid(lStorageid);
                            crmAcceDtlBo.setFileUrl(fileUrl);
                            crmAcceDtlMapper.add(crmAcceDtlBo);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } catch (Exception e) {

                    }

                }


        }
        resultModel.setCode(ResultStatus.SUCCESS.getCode());
        resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
        return resultModel;
    }
//实名认证提交
    @RequestMapping(value = "/api/upload2",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "多文件上传",notes = "多文件上传",position = 1,response = Object.class)
    public ResultModel saveCardPic2(HttpServletRequest request, HttpServletResponse response, UploadParam uploadParam){
        System.out.println("实名认证图片上传提交中。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。"+uploadParam.getFileCount());
        ResultModel resultModel=new ResultModel();
        String uploadType=uploadParam.getUploadType();
        if(StringUtil.isNullOrEmpty(uploadType)){
            uploadType= UploadContants.UPLOAD_TYPE_CRM;
        }
        int fileCount=uploadParam.getFileCount();
        String pReasonInfo2=uploadParam.getpReasonInfo2();
        String cCustNo=uploadParam.getcCustNo();
        response.setHeader("Access-Control-Allow-Origin", "*");
        String uploadPath = env.getProperty(ApplicationConstant.FILE_IMAGE_PATH);
        String imageDomain = env.getProperty(ApplicationConstant.IMAGE_SERVER_DOMAIN) ;
        List<AppFileBo> appFileList=new ArrayList<>();
        String lStorageidArray[]=new String[fileCount];
       /* for(int i=0;i<fileCount;i++){
            String lStorageid=tblobtSorageMapper.getTblobStorageSeq()+"";
            System.out.println("id"+i+"==================================="+lStorageid);
            lStorageidArray[i]=lStorageid;
        }*/
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            // 获得第1张图片（根据前台的name名称得到上传的文件）
            for(int i=0;i<fileCount;i++){
                List<MultipartFile> imgFileList = multipartHttpServletRequest.getFiles("file");
                MultipartFile imgFile1=multipartHttpServletRequest.getFile("file"+i);
                String lStorageid="";
                if(i==0){
                    AppFileBo appFileBo=new AppFileBo();
                    appFileBo.setcSubkeyId(pReasonInfo2);
                    lStorageid=shiMingRenZhengUploadMapper.getLstrorageId(appFileBo);
                }
                if(StringUtil.isNullOrEmpty(lStorageid)){
                    lStorageid=tblobtSorageMapper.getTblobStorageSeq()+"";
                }
                System.out.println("id"+i+"==================================="+lStorageid);
                if (!StringUtil.isNullOrEmpty(imgFile1)&&!imgFile1.isEmpty()) {
                    //获取前端传来的文件名
                    String fileName = imgFile1.getOriginalFilename();
                    // 设置存放图片文件的路径
                    String today= DateUtil.getToDay();
                    try {

                        AppFileBo appFileBo=new AppFileBo();
                        appFileBo.setlStorageid(lStorageid);
                        appFileBo.setUserId(cCustNo);
                        String fileExt = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length());
                        appFileBo.setcFilename(fileName);//文件名
                        appFileBo.setcFileSize(imgFile1.getSize()+"");//文件大小
                        String prex=lStorageid.substring(0,lStorageid.length()-1);
                        String filePath=uploadPath+uploadType+"/"+today+"/Tblobstorage/"+prex+"/"+appFileBo.getlStorageid()+"."+fileExt;
                        appFileBo.setcFilepath(filePath);
                            //利用文件流保存文件
                            File saveFile= new File(filePath);
                            File parentFile=saveFile.getParentFile();
                            if(!parentFile.exists()&&!parentFile.isDirectory()){
                                parentFile.mkdirs();
                            }
                            if(!saveFile.exists())
                            {
                                try {
                                    saveFile.createNewFile();
                                } catch (IOException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                            imgFile1.transferTo(saveFile);
                            System.out.println("文件上传路径："+filePath);
                            String appFileName=appFileBo.getlStorageid()+"."+fileExt;
                            String fileUrl = imageDomain  + "/"+uploadType+"/" +today+"/Tblobstorage/"+prex+"/"+appFileName;
                            appFileBo.setFileUrl(fileUrl);
                            appFileBo.setAppFileName(appFileName);
                            System.out.println("文件访问地址=========="+fileUrl);
                            //保存文件到crm数据库
                            appFileBo.setcSubkeyId(pReasonInfo2);
                            Map<String,Object> queryMap=new HashMap<>();
                            queryMap.put("userId",appFileBo.getUserId());
                            String deptNodeCode=shiMingRenZhengUploadMapper.getDeptNodeCode(queryMap);
                            if(StringUtil.isNullOrEmpty(deptNodeCode)){
                                deptNodeCode="";
                            }
                            appFileBo.setDeptNodeCode(deptNodeCode);
                            //实名认证文件处理

                            if(i==0){
                                appFileBo.setcCataLog("TCUSTREGISTERREQ_MAIN");
                                System.out.println("实名认证第一张图片pReasonInfo2========================="+pReasonInfo2);
                                 String lStrorageId=shiMingRenZhengUploadMapper.getLstrorageId(appFileBo);
                                 System.out.println("lStrorageId========================="+lStrorageId);
                                // appFileBo.setlStorageid(lStrorageId);
                                shiMingRenZhengUploadMapper.insertFirst(appFileBo);
                                //保存文件附件到app数据库
                                CrmAcceDtlBo crmAcceDtlBo=new CrmAcceDtlBo();
                                crmAcceDtlBo.setLStorageid(lStorageid);
                                crmAcceDtlBo.setFileUrl(fileUrl);
                                crmAcceDtlMapper.add(crmAcceDtlBo);
                            }else{
                                appFileBo.setcCataLog("TCUSTREGISTERREQ");
                                shiMingRenZhengUploadMapper.insertSecond(appFileBo);
                                //保存文件附件到app数据库
                                CrmAcceDtlBo crmAcceDtlBo=new CrmAcceDtlBo();
                                crmAcceDtlBo.setLStorageid(lStorageid);
                                crmAcceDtlBo.setFileUrl(fileUrl);
                                crmAcceDtlMapper.add(crmAcceDtlBo);
                            }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }

        }
        resultModel.setCode(ResultStatus.SUCCESS.getCode());
        resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
        return resultModel;
    }
//实名认证驳回提交

    @RequestMapping(value = "/api/bohui/upload",method = RequestMethod.POST)
    @Transactional
    @ResponseBody
    @ApiOperation(value = "驳回",notes = "驳回",position = 1,response = Object.class)
    public ResultModel bohui(HttpServletRequest request, HttpServletResponse response, UploadParam uploadParam, String imageJson){
        System.out.println("实名认证驳回提交中............................................................=========================================================================........");
        ResultModel resultModel=new ResultModel();
        String uploadType=uploadParam.getUploadType();
        if(StringUtil.isNullOrEmpty(uploadType)){
            uploadType= UploadContants.UPLOAD_TYPE_CRM;
        }
        String pReasonInfo2=uploadParam.getpReasonInfo2();
        String cCustNo=uploadParam.getcCustNo();
        response.setHeader("Access-Control-Allow-Origin", "*");
        String uploadPath = env.getProperty(ApplicationConstant.FILE_IMAGE_PATH);
        String imageDomain = env.getProperty(ApplicationConstant.IMAGE_SERVER_DOMAIN) ;
        List<AppFileBo> appFileList=new ArrayList<>();
       /* for(int i=0;i<fileCount;i++){
            String lStorageid=tblobtSorageMapper.getTblobStorageSeq()+"";
            System.out.println("id"+i+"==================================="+lStorageid);
            lStorageidArray[i]=lStorageid;
        }*/
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            // 获得第1张图片（根据前台的name名称得到上传的文件）
            int fileCount=uploadParam.getFileCount();
            for(int i=0;i<fileCount;i++){
                List<MultipartFile> imgFileList = multipartHttpServletRequest.getFiles("file");
                MultipartFile imgFile1=multipartHttpServletRequest.getFile("file"+i);
                String lStorageid=tblobtSorageMapper.getTblobStorageSeq()+"";
                //驳回的时候，认证的时候，图片没有全部删除
                //如果全部旧的 删除了则和认证的方法一样
               // if(i==0){
                 //   AppFileBo appFileBo=new AppFileBo();
                   // appFileBo.setcSubkeyId(pReasonInfo2);
                    //lStorageid=shiMingRenZhengUploadMapper.getLstrorageId(appFileBo);
               // }
                System.out.println("id"+i+"==================================="+lStorageid);
                if (!StringUtil.isNullOrEmpty(imgFile1)&&!imgFile1.isEmpty()) {
                    //获取前端传来的文件名
                    String fileName = imgFile1.getOriginalFilename();
                    // 设置存放图片文件的路径
                    String today= DateUtil.getToDay();
                    try {

                        AppFileBo appFileBo = new AppFileBo();
                        appFileBo.setlStorageid(lStorageid);
                        appFileBo.setUserId(cCustNo);
                        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
                        appFileBo.setcFilename(fileName);//文件名
                        appFileBo.setcFileSize(imgFile1.getSize() + "");//文件大小
                        String prex = lStorageid.substring(0, lStorageid.length() - 1);
                        String filePath = uploadPath + uploadType + "/" + today + "/Tblobstorage/" + prex + "/" + appFileBo.getlStorageid() + "." + fileExt;
                        appFileBo.setcFilepath(filePath);
                        //利用文件流保存文件
                        File saveFile = new File(filePath);
                        File parentFile = saveFile.getParentFile();
                        if (!parentFile.exists() && !parentFile.isDirectory()) {
                            parentFile.mkdirs();
                        }
                        if (!saveFile.exists()) {
                            try {
                                saveFile.createNewFile();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                        imgFile1.transferTo(saveFile);
                        System.out.println("文件上传路径：" + filePath);
                        String appFileName = appFileBo.getlStorageid() + "." + fileExt;
                        String fileUrl = imageDomain + "/" + uploadType + "/" + today + "/Tblobstorage/" + prex + "/" + appFileName;
                        appFileBo.setFileUrl(fileUrl);
                        appFileBo.setAppFileName(appFileName);
                        System.out.println("文件访问地址==========" + fileUrl);
                        //保存文件到crm数据库
                        appFileBo.setcSubkeyId(pReasonInfo2);
                        Map<String, Object> queryMap = new HashMap<>();
                        queryMap.put("userId", appFileBo.getUserId());
                        String deptNodeCode = shiMingRenZhengUploadMapper.getDeptNodeCode(queryMap);
                        if (StringUtil.isNullOrEmpty(deptNodeCode)) {
                            deptNodeCode = "";
                        }
                        appFileBo.setDeptNodeCode(deptNodeCode);
                        //实名认证文件处理

                 /*       if(i==0){
                            appFileBo.setcCataLog("TCUSTREGISTERREQ_MAIN");
                            System.out.println("实名认证第一张图片pReasonInfo2========================="+pReasonInfo2);
                            String lStrorageId=shiMingRenZhengUploadMapper.getLstrorageId(appFileBo);
                            System.out.println("lStrorageId========================="+lStrorageId);
                            // appFileBo.setlStorageid(lStrorageId);
                            shiMingRenZhengUploadMapper.insertFirst(appFileBo);
                            //保存文件附件到app数据库
                            CrmAcceDtlBo crmAcceDtlBo=new CrmAcceDtlBo();
                            crmAcceDtlBo.setLStorageid(lStorageid);
                            crmAcceDtlBo.setFileUrl(fileUrl);
                            crmAcceDtlMapper.add(crmAcceDtlBo);
                        }else{*/
                        appFileBo.setcCataLog("TCUSTREGISTERREQ");
                        shiMingRenZhengUploadMapper.insertSecond(appFileBo);
                        //保存文件附件到app数据库
                        CrmAcceDtlBo crmAcceDtlBo = new CrmAcceDtlBo();
                        crmAcceDtlBo.setLStorageid(lStorageid);
                        crmAcceDtlBo.setFileUrl(fileUrl);
                        crmAcceDtlMapper.add(crmAcceDtlBo);
                  /*  }*/

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }

        }
        resultModel.setCode(ResultStatus.SUCCESS.getCode());
        resultModel.setMessage(ResultStatus.SUCCESS.getMessage());
        return resultModel;
    }


}
